local base = _G
module("Function.stock_management")

local config = base.require("Configure.config")
local http = base.require("Library.LuaSocket.socket.http")
local xml = base.require("Library.LuaXML2.LuaXML2")

function Query(stock_ID)
	if stock_ID == nil then
		return nil
	end
	local baseurl = config.GetValue("baseurl") .. "stocks.php"
	--base.io.write("DBG:baseurl = " .. baseurl .. "\n")
	local s,c = http.request(baseurl .. "?action=query&sn=" .. stock_ID)
	--[[
	base.io.write("DBG:Code is " .. c .. "\n")
	base.io.write("DBG:Raw XML content:\n" .. s .. "\n")
	--]]
	if c ~= 200 then
		return -1,c
	end
	
	local t = xml.collect(s)
	t=t[2][1]
	return t
end

function Query2(stock_ID)
	t = Query(stock_ID)
	if t == nil then
		return {}
	end
	t2 = {}
	for k in base.pairs(t) do
		local tk = t[k]["label"]
		if tk ~= nil then
			t2[tk] = t[k][1]
		end
	end
	return t2
end

function Add(t)
	local baseurl = config.baseurl .. "stocks.php"
	local url = baseurl .. "?action=add&"
	for k,v in base.pairs(t) do
		url = url .. k .. "=" .. v .. "&"
	end
	url = base.string.sub(s,1,-2)
	
	base.io.write("DBG:URL is: " .. url .. "\n")
	
	local s = http.request(url)
	if s == nil then
		return -1
	end
	local t = xml.collect(s)
	t=t[2][1]
	return t
end
